#!/bin/bash

# =====================================================
# 快速启动脚本 - 战略规划与预算预测AI智能体系统
# =====================================================

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}=====================================================${NC}"
echo -e "${BLUE}  战略规划与预算预测AI智能体系统 - 快速启动${NC}"
echo -e "${BLUE}=====================================================${NC}"

# 检查Python环境
echo -e "\n${YELLOW}1. 检查Python环境...${NC}"
if ! command -v python3 &> /dev/null; then
    echo -e "${RED}❌ Python3未安装${NC}"
    exit 1
fi

PYTHON_VERSION=$(python3 --version | cut -d' ' -f2)
echo -e "${GREEN}✅ Python版本: $PYTHON_VERSION${NC}"

# 检查虚拟环境
echo -e "\n${YELLOW}2. 检查虚拟环境...${NC}"
if [ ! -d "venv" ]; then
    echo -e "${YELLOW}⚠️  虚拟环境不存在，正在创建...${NC}"
    python3 -m venv venv
    echo -e "${GREEN}✅ 虚拟环境创建成功${NC}"
fi

# 激活虚拟环境
echo -e "\n${YELLOW}3. 激活虚拟环境...${NC}"
source venv/bin/activate
echo -e "${GREEN}✅ 虚拟环境已激活${NC}"

# 安装依赖
echo -e "\n${YELLOW}4. 安装Python依赖...${NC}"
if [ ! -f "requirements.txt" ]; then
    echo -e "${RED}❌ requirements.txt文件不存在${NC}"
    exit 1
fi

pip install -r requirements.txt
if [ $? -eq 0 ]; then
    echo -e "${GREEN}✅ 依赖安装成功${NC}"
else
    echo -e "${RED}❌ 依赖安装失败${NC}"
    exit 1
fi

# 测试MySQL连接
echo -e "\n${YELLOW}5. 测试MySQL连接...${NC}"
python3 test_mysql_connection.py
if [ $? -eq 0 ]; then
    echo -e "${GREEN}✅ MySQL连接测试通过${NC}"
else
    echo -e "${RED}❌ MySQL连接测试失败${NC}"
    echo -e "${YELLOW}请检查MySQL服务状态和配置${NC}"
    echo -e "${YELLOW}可以尝试: sudo systemctl status mysql${NC}"
    exit 1
fi

# 初始化数据库
echo -e "\n${YELLOW}6. 初始化数据库...${NC}"
if [ -f "init_mysql_db.sh" ]; then
    chmod +x init_mysql_db.sh
    ./init_mysql_db.sh
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✅ 数据库初始化成功${NC}"
    else
        echo -e "${YELLOW}⚠️  数据库初始化警告（可能表已存在）${NC}"
    fi
else
    echo -e "${YELLOW}⚠️  数据库初始化脚本不存在，跳过${NC}"
fi

# 设置环境变量
echo -e "\n${YELLOW}7. 设置环境变量...${NC}"
export MYSQL_PASSWORD="neo..6555894"
export MYSQL_DATABASE="qilu_db"
export FLASK_ENV="development"
export FLASK_DEBUG="true"
echo -e "${GREEN}✅ 环境变量设置完成${NC}"

# 启动应用
echo -e "\n${YELLOW}8. 启动Flask应用...${NC}"
echo -e "${GREEN}🚀 应用正在启动，请稍候...${NC}"
echo -e "${BLUE}访问地址: http://localhost:5000${NC}"
echo -e "${BLUE}API文档: http://localhost:5000/api/health${NC}"
echo -e "${YELLOW}按 Ctrl+C 停止应用${NC}"

# 启动Flask应用
python3 src/main.py
